package org.tech4j.common.core.sign.service;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tech4j.common.core.constant.Constants;
import org.tech4j.common.core.sign.api.AppSignData;
import org.tech4j.common.core.sign.api.SignParameters;
import org.tech4j.common.core.sign.api.VerifyResult;
import org.tech4j.common.core.sign.api.VerifySupplier;
import org.tech4j.common.core.sign.config.SignProperties;
import org.tech4j.common.core.sign.extractor.SignParameterExtractor;
import org.tech4j.common.core.sign.provider.SignProvider;
import org.tech4j.common.utils.path.PathMatchUtils;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;
import java.util.function.BiFunction;

/**
 * @program: tech4j-common
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/2 19:42
 **/
public class ComposableSignService implements SignService {
    private static final Logger log = LoggerFactory.getLogger(ComposableSignService.class);

    private final SignProperties properties;
    private final SignParameterExtractor extractor;
    private final SignProvider signProvider;

    public ComposableSignService(SignParameterExtractor extractor, SignProvider signProvider) {
        // 默认5分钟
        this.properties = new SignProperties(5);
        this.extractor = extractor;
        this.signProvider = signProvider;
    }

    public ComposableSignService(SignParameterExtractor extractor, SignProvider signProvider, SignProperties properties) {
        this.extractor = extractor;
        this.signProvider = signProvider;
        this.properties = properties;
    }

    @Override
    public VerifyResult signatureVerify(AppSignData signData, String requestBody) {
        SignParameters signParameters = extractor.extract(requestBody);
        String appKey = signParameters.getAppKey();
        if (StringUtils.isBlank(appKey)) {
            return VerifyResult.fail(Constants.SIGN_APP_KEY_IS_NOT_EXIST);
        }
        if (!StringUtils.equals(signData.getAppKey(), appKey)) {
            return VerifyResult.fail(Constants.SIGN_APP_KEY_IS_MISMATCH);
        }
        return verify(signParameters, signData, signProvider::generateSign);
    }

    @Override
    public VerifyResult signatureVerify(AppSignData signData, HttpServletRequest request) {
        return signatureVerify(signData, request, signProvider::generateSign);
    }

    @Override
    public VerifyResult signatureVerify(AppSignData signData, HttpServletRequest request, String paramType, String paramKey) {
        return signatureVerify(signData, request, paramType, paramKey, signProvider::generateSign);
    }

    private VerifyResult signatureVerify(final AppSignData signData, final HttpServletRequest request, final String paramType, final String paramKey, final BiFunction<String, SignParameters, String> signFunction) {
        SignParameters signParameters = extractor.extract(request, paramType, paramKey);
        String appKey = signParameters.getAppKey();
        if (StringUtils.isBlank(appKey)) {
            return VerifyResult.fail(Constants.SIGN_APP_KEY_IS_NOT_EXIST);
        }
        if (!StringUtils.equals(signData.getAppKey(), appKey)) {
            return VerifyResult.fail(Constants.SIGN_APP_KEY_IS_MISMATCH);
        }

        return verify(signParameters, signData, signFunction);
    }

    private VerifyResult signatureVerify(final AppSignData signData, final HttpServletRequest request, final BiFunction<String, SignParameters, String> signFunction) {
        SignParameters signParameters = extractor.extract(request);
        String appKey = signParameters.getAppKey();
        if (StringUtils.isBlank(appKey)) {
            return VerifyResult.fail(Constants.SIGN_APP_KEY_IS_NOT_EXIST);
        }
        if (!StringUtils.equals(signData.getAppKey(), appKey)) {
            return VerifyResult.fail(Constants.SIGN_APP_KEY_IS_MISMATCH);
        }
        return verify(signParameters, signData, signFunction);
    }

    private VerifyResult verify(final SignParameters signParameters,
                                final AppSignData signData,
                                final BiFunction<String, SignParameters, String> signFunction) {

        return VerifySupplier
                .apply(() -> verifySignParameters(signParameters))
                .and(() -> verifyExpires(signParameters))
                .and(() -> verifyAuthConfig(signData, signParameters))
                .and(() -> verifyPath(signData, signParameters))
                .and(() -> verifySign(signData.getAppSecret(), signParameters, signFunction))
                .verify();

    }

    private VerifyResult verifySignParameters(final SignParameters signParameters) {
        boolean success = StringUtils.isNoneBlank(signParameters.getAppKey())
                && StringUtils.isNoneBlank(signParameters.getTimestamp())
                && StringUtils.isNoneBlank(signParameters.getSignature());
        if (success) {
            return VerifyResult.success();
        }
        log.error("sign parameters are incomplete,{}", signParameters);
        return VerifyResult.fail(Constants.SIGN_PARAMS_ERROR);
    }

    private VerifyResult verifyExpires(final SignParameters signParameters) {
        final LocalDateTime start = LocalDateTime.ofEpochSecond(Long.parseLong(signParameters.getTimestamp()) / 1000, 0, OffsetDateTime.now().getOffset());
        final LocalDateTime now = LocalDateTime.now();
        final long between = start.until(now, ChronoUnit.MINUTES);
        if (Math.abs(between) <= properties.getExpires()) {
            return VerifyResult.success();
        }
        return VerifyResult.fail(String.format("The signature timestamp has exceeded %s minutes!", properties.getExpires()));
    }

    private VerifyResult verifyAuthConfig(final AppSignData signData, final SignParameters signParameters) {
        if (Objects.isNull(signData) || BooleanUtils.isFalse(signData.getEnabled())) {
            log.error("sign APP_KEY does not exist or has been disabled,{}", signParameters.getAppKey());
            return VerifyResult.fail(Constants.SIGN_APP_KEY_IS_NOT_EXIST);
        }
        return VerifyResult.success();
    }

    private VerifyResult verifyPath(final AppSignData signData, final SignParameters signParameters) {
        if (BooleanUtils.isNotTrue(signData.getOpen())) {
            return VerifyResult.success();
        }

        List<AppSignData.PathData> pathDataList = signData.getPathDataList();
        if (CollectionUtils.isEmpty(pathDataList)) {
            log.error("You have not configured the sign path:{}", signParameters.getAppKey());
            return VerifyResult.fail(Constants.SIGN_PATH_NOT_EXIST);
        }

        boolean match = pathDataList.stream().filter(AppSignData.PathData::getEnabled)
                .anyMatch(e -> PathMatchUtils.match(e.getPath(), signParameters.getUri().getPath()));
        if (!match) {
            log.error("You have not configured the sign path:{},{}", signParameters.getAppKey(), signParameters.getUri().getPath());
            return VerifyResult.fail(Constants.SIGN_PATH_NOT_EXIST);
        }
        return VerifyResult.success();
    }

    private VerifyResult verifySign(final String signKey,
                                    final SignParameters signParameters,
                                    final BiFunction<String, SignParameters, String> signFunction) {

        String sign = signFunction.apply(signKey, signParameters);

        boolean result = StringUtils.equals(sign, signParameters.getSignature());
        if (!result) {
            log.error("the SignUtils generated signature value is:{},the accepted value is:{}", sign, signParameters.getSignature());
            return VerifyResult.fail(Constants.SIGN_VALUE_IS_ERROR);
        }
        return VerifyResult.success();
    }
}
